<template>
  <NavHeader/>
  <bread-crumb/>
  <div class="w-1200px m-auto">
    <div class="relative -mt-40px flex justify-end">
      <button type="button" class="back-btn" @click="linkTo('process')">返回</button>
    </div>
    <div class="mt-10px w-full min-h-860px bg-hex-FFF pt-25px pb-30px">
      <h3 class="text-18px text-center">附件出题</h3>
      <div class="mt-60px pl-250px">
        <el-form ref="ruleFormRef" :rules="rules" :model="createForm" label-width="140px" size="large" status-icon>
          <el-form-item label="学科" style="width: 620px">
            <h3 class="text-14px">{{ createForm.xkmc }}</h3>
          </el-form-item>
          <el-form-item label="答题卡名称" prop="dtkmc" style="width: 620px">
            <el-input v-model="createForm.dtkmc" placeholder="请输入答题卡名称"/>
          </el-form-item>
          <el-form-item label="答题卡别名" style="width: 620px">
            <el-input v-model="createForm.dtkbm" placeholder="请输入答题卡别名"/>
          </el-form-item>
          <el-form-item label="及格分数" prop="jgfs" style="width: 620px">
            <el-input v-model="createForm.jgfs" placeholder="请输入及格分数"/>
          </el-form-item>
          <el-form-item label="优秀分数" prop="yxfs" style="width: 620px">
            <el-input v-model="createForm.yxfs" placeholder="请输入优秀分数"/>
          </el-form-item>
          <el-form-item label="流程类型" prop="lclx" style="width: 620px">
            <el-radio-group v-model="createForm.lclx">
              <el-radio v-for="item in lc_type_list" :label="item.value">{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="阅卷流程" prop="fj_choose" style="width: 620px">
            <el-radio-group v-model="createForm.fj_choose">
              <el-radio v-for="item in yjlc" :label="item.value" @change="fileList = []">{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item>
            <el-upload v-if="createForm.fj_choose === '1'"
                       action=""
                       :auto-upload="false"
                       :show-file-list="false"
                       :on-change="uploadFile"
                       v-loading.fullscreen.lock="fullscreenLoading"
                       accept=".jpg,.png,.jpeg"
                       class="upload-demo"
            >
              <el-button type="primary" color="#003eee">
                <el-icon :size="24">
                  <UploadFilled/>
                </el-icon>
                <span>上传文件</span>
              </el-button>
              <template #tip>
                <div class="el-upload__tip">
                  上传文件格式支持 jpg,png,jpeg
                </div>
              </template>
            </el-upload>
            <div v-else-if="createForm.fj_choose === '2'">
              <el-button type="primary" color="#003eee" @click="launchClient">
                <el-icon :size="24">
                  <Promotion/>
                </el-icon>
                <span>启动客户端</span>
              </el-button>
            </div>
            <div v-else>
              <el-button type="primary" color="#003eee" @click="chooseCard">
                <el-icon :size="24">
                  <Plus/>
                </el-icon>
                <span>请选择答题卡</span>
              </el-button>
            </div>
          </el-form-item>
          <el-form-item v-if="fileList.length > 0" label="文件列表">
            <div class="flex">
              <div class="w-370px">名称</div>
              <div class="w-200px">操作</div>
            </div>
            <div class="flex" v-for="(item,index) in fileList">
              <div class="w-370px truncate">{{ item.name }}</div>
              <div class="w-200px">
                <el-link :underline="false" @click="filePreview(item)">预览</el-link>
                <el-link class="ml-10px" :underline="false" @click="downloadFile(item)">下载</el-link>
                <el-link class="ml-10px" :underline="false" @click="delFile(index)">删除</el-link>
              </div>
            </div>
          </el-form-item>
          <el-form-item>
            <div class="mt-50px pl-50px">
              <el-button class="mr-20px" @click="linkTo('process')"><span class="px-40px">取消</span></el-button>
              <el-button type="primary" color="#003eee" @click="handleSubmit(ruleFormRef)"><span
                class="px-40px">确定</span></el-button>
            </div>


          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
  <el-dialog v-model="previewDialogVisible" title="文件预览"
             width="850px"
             custom-class="dialogTrick"
             append-to-body>
    <div class="w-full h-700px overflow-auto">
      <img class="w-full" v-if="fileType === 'img'" :src="fileUrl" alt="Preview Image"/>
      <video class="w-full h-full" controls v-if="fileType === 'mp4'" :src="fileUrl"></video>
      <iframe class="w-full h-full" v-if="fileType === 'file'" :src="fileUrl" frameborder="0"></iframe>
    </div>

  </el-dialog>
  <el-dialog
    v-model="dialogVisible"
    title="答题卡选择"
    width="980px"
    custom-class="dialogTrick"
    append-to-body
  >
    <el-form :inline="true" class="flex justify-between" size="large">
      <el-form-item label="考试时间筛选">
        <el-date-picker
          v-model="exam_time"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          @change="handleDateChange"
          size="large"
        />
      </el-form-item>
      <div>
        <el-form-item style="margin-right: 10px">
          <el-input v-model="keyword" style="width: 200px;" placeholder="请输入关键字" clearable @keyup.enter="filterData"
                    @clear="filterData"/>
        </el-form-item>
        <el-form-item>
          <el-button color="#003eee" type="primary" @click="filterData">搜索</el-button>
        </el-form-item>

      </div>

    </el-form>
    <div v-if="cardList.length > 0">
      <ul class="card-list py-15px pl-20px">
        <li v-for="item in cardList" class="relative py-15px" :class="chooseCheck === item.zs_id?'selected':''">
          <div class="choose">
            <p class="set-check">
              <input type="radio" :id="item.zs_id" :value="item.zs_id" v-model="chooseCheck">
              <label :for="item.zs_id"></label>
            </p>
          </div>
          <div class="w-162px h-108px m-auto overflow-hidden">
            <img class="w-full"
                 :src="item.fj_content[0].url"
                 alt="">
          </div>
          <h3 class="mt-10px mb-10px px-20px text-13px leading-20px truncate text-center">{{item.zs_name}}</h3>
          <button type="button" class="op-btn block m-auto" :disabled="item.not_allowed" @click="imgShow(item)">查看</button>
        </li>
      </ul>
      <div class="mt-20px page-new flex justify-end">
        <el-pagination v-model:current-page="cur_page" v-model:page-size="limit" layout="total,prev, pager, next" :total="total" :background="true" @current-change="handleSelectionChange"></el-pagination>
      </div>
    </div>
    <div v-else class="no-data">
      <div>
        <h3 class="no-data-img"></h3>
        <h4 class="mt-25px text-18px text-hex-0048e5 text-center">暂无数据</h4>
      </div>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false" class="mr-15px" size="large">
          <span class="px-10px">取消</span>
        </el-button>
        <el-button size="large" color="#003eee" type="primary" :disabled="chooseCheck === ''" @click="chooseCardSub">
          <span class="px-10px">确定</span>
        </el-button>
      </span>
    </template>

  </el-dialog>
  <div class="loading-mask" v-if="scanLoading">
    <div class="text-center">
      <div class="loading-icon"></div>
      <h3 class="text-16px text-center text-hex-959595">客户端处理中，耐心等待……</h3>
    </div>
  </div>
  <div class="preview-box" v-if="showPreview">
    <el-icon class="preview-close cursor-pointer" @click="showPreview = false"><CloseBold /></el-icon>
    <el-carousel class="h-full overflow-y-auto" :autoplay="false" indicator-position="none">
      <el-carousel-item v-for="item in imgPreview" :key="item">
        <img class="m-auto block" :src="item.url" alt="">
      </el-carousel-item>
    </el-carousel>
  </div>
  <commonFooter/>
</template>
<route lang="json">
{
"meta":{
"title":"附件出题",
"breadcrumb": true
}
}
</route>
<script setup>
import {useRouter} from "vue-router";
import request from "~/utils/request";
import {REQUEST} from "~/utils/request";
import {user} from "~/store";

const router = useRouter();
const route = useRoute();
const linkTo = (name) => {
  router.push({name});
};
const rules = $ref({
  dtkmc: [{required: true, message: '请输入答题卡名称', trigger: 'blur'}],
  jgfs: [{required: true, message: '请输入及格分数', trigger: 'blur'}],
  yxfs: [{required: true, message: '请输入优秀分数', trigger: 'blur'}],
  lclx: [{required: true, message: '请选择流程类型', trigger: 'change'}],
  fj_choose: [{required: true, message: '请选择阅卷流程', trigger: 'change'}],
})
const ruleFormRef = ref(null);
let createForm = $ref({
  xkmc: '',
  dtkmc: '',
  dtkbm: '',
  jgfs: '',
  yxfs: '',
  lclx: '',
  fj_choose: '1'
})
let lc_type_list = [{
  value: '0',
  label: '常规'
}, {
  value: '1',
  label: '自定义框选'
}, {
  value: '2',
  label: '无定位点框选（第三方答题卡）'
}]
let yjlc = [{
  value: '1',
  label: '上传文件'
}, {
  value: '2',
  label: '模板预扫描'
}, {
  value: '3',
  label: '沿用答题卡'
}]
function handleAutoCompleteTask(val) {
  const { gid, pid, cid } = JSON.parse(sessionStorage.getItem('StepId'));
  // handleCompleteTask(gid, pid, cid)
  const _ykl_lc_ = JSON.parse(sessionStorage.getItem('ykl_lc'));
  _ykl_lc_.processList[gid][pid][cid] = val || 1;
  return request({
    url: '/yzy/kmksyjlc/save',
    data: {
      ykl_id: _ykl_lc_.ykl_id,
      yk: {
        ykl_lc: JSON.stringify(_ykl_lc_),
      },
    },
  }).then((res) => {
    if (res.code === '1') {
      ElMessage({
        message: '操作成功',
        type: 'success',
        grouping: true,
      });
      sessionStorage.setItem('ykl_lc', JSON.stringify(_ykl_lc_));
      nextTick(()=>{
        router.back();
      })

    }
  }).catch(() => {
    ElMessage({
      message: '操作失败',
      type: 'error',
      grouping: true,
    });
  });
}

const handleCancel = () => {
  router.back();
}

const handleSubmit = async (formEl) => {
  if (!formEl) return;

  formEl.validate(async (valid, fields) => {
    if (valid) {
      if (fileList.length === 0) {
        ElMessage({
          type: "warning",
          message: "请先上传附件！",
        });
      } else {
        request({
          url: '/yzy/ksjh/fjct_edit',
          data: {
            zs_id: zs_id,
            ze_id: ze_id,
            zs_name: createForm.dtkmc,
            zs_alias: createForm.dtkbm,
            zs_lctype: createForm.lclx,
            fj_choose: createForm.fj_choose,
            fj_content: fileList,
            ze_pass_score: createForm.jgfs,
            ze_max_score: createForm.yxfs
          }
        }).then(res => {
          if (res.code === '1') {
            ElMessage.success("附件出题编辑成功！");
            // 需要跳转到新流程页面
            handleAutoCompleteTask();

          }
        })
      }
    } else {
      console.log("error submit!", fields);
    }
  });
}

let dialogVisible = $ref(false)
let chooseCheck = $ref('');
let ze_id = $ref('');
let zs_id = $ref('');
if (route.params.ze_id) {
  ze_id = route.params.ze_id;
  zs_id = route.params.zs_id;
  getDetail();
}
let fullscreenLoading = $ref(false)
let fileList = $ref([])
let scanLoading = $ref(false)

function getDetail() {
  request({
    url: "/yzy/ksjh/fjct_detail",
    data: {
      ze_id: ze_id,
      zs_id: zs_id
    },
  }).then((res) => {
    if (res.code === "1") {
      createForm.xkmc = res.data.one_info.ze_xueke_name;
      createForm.dtkmc = res.data.one_info.zs_name;
      createForm.dtkbm = res.data.one_info.zs_alias;
      createForm.jgfs = res.data.one_info.ze_pass_score;
      createForm.yxfs = res.data.one_info.ze_max_score;
      createForm.lclx = res.data.one_info.zs_lctype;
      if (res.data.one_info.fj_choose === '0') {
        createForm.fj_choose = '1';
      } else {
        createForm.fj_choose = res.data.one_info.fj_choose;
      }

      fileList = [];
      if (res.data.one_info.fj_content !== '') {
        let i_arr = res.data.one_info.fj_content.split('**');
        for (let i in i_arr) {
          let f_obj = {
            name: i_arr[i].split('##')[0],
            url: i_arr[i].split('##')[1]
          }
          fileList.push(f_obj);
        }
      }

    }
  });
}

const uploadFile = (file) => {
  // console.log(file, 87)
  fullscreenLoading = true;
  REQUEST.upload({
    url: '/upload/main/file',
    data: {
      filedata: file.raw,
      mod: 'upload',
      action: 'main',
      do: 'file',
      urltype: '1'
    }
  }).then(res => {
    fullscreenLoading = false;
    if (res.code === '1') {
      // console.log(res.data, 89)
      let file_info = {
        name: res.data.file_name,
        url: res.data.url
      }
      fileList.push(file_info);
    } else {
      ElMessage({
        type: "warning",
        message: "上传失败",
      });
    }
  })
}
let previewDialogVisible = $ref(false)
let fileType = $ref('')
let fileUrl = $ref('')
const filePreview = (item) => {
  previewDialogVisible = true;

  if (/\.(jpg|png|jpeg)/.test(item.url)) {
    fileType = 'img';
    fileUrl = item.url;
  } else if (/\.mp4/.test(item.url)) {
    fileType = 'mp4';
    fileUrl = item.url;
  } else if (/\.(docx|doc|pdf|ppt|pptx|xls|xlsx)/.test(item.url)) {
    fileType = 'file';
    fileUrl = 'https://view.officeapps.live.com/op/view.aspx?src=' + item.url;
  }
}
const downloadFile = (item) => {
  window.open(item.url, '_blank')
}
const delFile = (index) => {
  fileList.splice(index, 1)
}
const launchClient = () => {
  scanLoading = true;
  let scan_batch = parseInt(new Date().getTime() / 1000) + randomString(5);
  let clientLink = 'bozeduyuejuan://' + user.value.token + ',0,' + window.GLOBAL_CONFIG.yzy + ',pre_scan,' + scan_batch;
  window.open(clientLink, '_blank');
  getScanStatus(scan_batch);
}

function randomString(e) {
  e = e || 32;
  var t = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz123456789",
    a = t.length,
    n = "";
  for (let i = 0; i < e; i++) n += t.charAt(Math.floor(Math.random() * a));
  return n
}

let timer = null;

function interval(func, wait) {
  let interv = () => {
    func.call(null);
    timer = setTimeout(interv, wait);
  };
  timer = setTimeout(interv, wait);
}

function getScanStatus(scan_batch) {
  request({
    url: "/yzy/kmksyjlc/pre_scan_get",
    data: {
      tag: scan_batch
    },
  }).then((res) => {
    if (res.code === "1") {
      if (res.data.files.length === 0) {

        interval(() => {
          if (timer) {
            clearTimeout(timer);
            timer = null;
          }
          getScanStatus(scan_batch)
        }, 10000);
      } else {
        scanLoading = false;
        if (timer) {
          clearTimeout(timer);
          timer = null;
        }
        fileList = [];
        for (let i = 0; i < res.data.files.length; i++) {
          let file_info = {
            name: '模板_' + (i + 1),
            url: window.GLOBAL_CONFIG.yzy + '/' + res.data.files[i]
          }
          fileList.push(file_info);
        }
      }
    }
  })
}

let limit = $ref(8)
let total = $ref(0)
let cur_page = $ref(1)
let exam_time = $ref([])
let keyword = $ref('')
let cardList = $ref([]);
const chooseCard = () => {
  getListData();
  chooseCheck = '';
  dialogVisible = true;

}

function getListData() {
  let data = {
    page: cur_page,
    limit: limit,
    keyword: keyword
  }
  if(exam_time && exam_time.length > 0) {
    data.date_start = exam_time[0];
    data.date_end = exam_time[1];
  } else {
    data.date_start = '';
    data.date_end = '';
  }
  request({
    url: "/yzy/ksjh/before_paper",
    data: data,
  }).then((res) => {
    if (res.code === '1') {
      cardList = res.data.page_data;
      total = Number(res.data.total_rows);
      cur_page = Number(res.data.page_now);
      for(let i in cardList) {
        for(let j in cardList[i].fj_content) {
          cardList[i].not_allowed = /\.(docx|doc|pdf|ppt|pptx|xls|xlsx|mp4)/.test(cardList[i].fj_content[j].url);
        }
      }
    }
  })
}

const handleDateChange = (val) => {
  if (val) {
    exam_time = [val[0], val[1]];
  } else {
    exam_time = [];
  }
  cur_page = 1;
  getListData();
}
const handleSelectionChange = (val) => {
  cur_page = val;
  getListData();
};
function filterData() {
  cur_page = 1;
  getListData();
}
function chooseCardSub() {
  for(let i in cardList) {
    if(cardList[i].zs_id === chooseCheck) {
      fileList = cardList[i].fj_content;
    }
  }
  dialogVisible = false;

}
let imgPreview = $ref([]);
let showPreview = $ref(false)
function imgShow(item) {
  imgPreview = item.fj_content;
  showPreview = true;
}
</script>

<style lang="scss">

.dialogTrick .el-dialog__footer {
  text-align: center;
}
</style>

<style lang="scss" scoped>
::v-deep .el-radio__input.is-checked .el-radio__inner {
  border-color: #003eee;
  background: #003eee;
}

::v-deep .el-radio__input.is-checked + .el-radio__label {
  color: #003eee;
}
::v-deep .el-carousel__container{
  height: 100%;
}

.card-list {
  display: flex;
  flex-wrap: wrap;
  max-height: 515px;
  overflow-y: auto;

  li {
    width: 203px;
    background: #ffffff;
    border: 2px solid #cacaca;
    border-radius: 10px;
    margin-right: 30px;
    margin-bottom: 30px;

    &.selected {
      border-color: #003eee;
    }

    &:nth-child(4n) {
      margin-right: 0;
    }

    &:hover {
      .card-pop {
        display: flex;
      }
    }

    .card-title {
      width: 100%;
      font-size: 13px;
      line-height: 15px;
    }
  }

  .card-pop {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    border-radius: 10px;
    z-index: 30;
    background: rgba(0, 0, 0, .45);
    display: none;
    align-items: center;
    justify-content: center;
  }
}

.op-btn {
  width: 60px;
  height: 30px;
  background: #fff;
  border: 1px solid #003eee;
  border-radius: 2px;
  font-size: 14px;
  color: #003eee;
  text-align: center;
  &:disabled{
    background: #ccc;
    border-color: #ccc;
    color: #fff;
    pointer-events: none;
  }
}

.choose {
  position: absolute;
  left: -12px;
  top: -12px;
  z-index: 50;
}

.set-check {
  position: relative;
  z-index: 40;
  width: 25px;
  height: 25px;

  label {
    position: absolute;
    left: 0;
    width: 25px;
    height: 25px;
    cursor: pointer;
    background: #fff;
    border-radius: 4px;
    box-shadow: 0 0 4px rgba(0, 0, 0, 0.18);
  }

  input[type=radio] {
    width: 25px;
    height: 25px;
    opacity: 0;

    &:checked + label {
      background: #003eee;
    }

    &:checked + label:after {
      content: '';
      width: 16px;
      height: 10px;
      position: absolute;
      top: 5px;
      left: 4px;
      border: 3px solid #fff;
      border-top: none;
      border-right: none;
      -moz-transform: rotate(-45deg);
      -ms-transform: rotate(-45deg);
      -webkit-transform: rotate(-45deg);
      transform: rotate(-45deg);
    }
  }

}

.loading-mask {
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  z-index: 1500;
  background: rgba(255, 255, 255, .6);
  display: flex;
  justify-content: center;
  align-items: center;
}

.loading-mask .loading-icon {
  margin: 0 auto 15px;
  width: 72px;
  height: 72px;
  background: url("/images/loading-new.gif") center no-repeat;
}
.no-data {
  width: 100%;
  height: 300px;
  display: flex;
  justify-content: center;
  align-items: center;

  .no-data-img {
    width: 233px;
    height: 199px;
    background: url("/images/no-data.png") center no-repeat;
  }
}
.preview-box{
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  z-index: 2100;
  background: rgba(0,0,0,.5);
  .preview-close{
    position: absolute;
    right: 15px;
    top: 15px;
    font-size: 40px;
    color: #fff;
    z-index:2200 ;
  }
  .el-carousel__item{
    display: flex;
    align-items: center;
    justify-content: center;
    overflow-y: auto;
  }
  img{
    max-width: 80% !important;
  }
}
</style>
